import Vue from 'vue'
import Router from 'vue-router'
import {getLoginUser} from '@/utils/storage'
import store from '@/store'

Vue.use(Router)

const originalPush = Router.prototype.push
Router.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
}


const router = new Router({
  mode: 'history', // 去掉url中的#
  scrollBehavior: () => ({ y: 0 }),
  routes: [{
	  path: '/login',
	  name: 'login',
	  component: (resolve) => require(['@/views/login'], resolve)
  }, {
	  path: '',
	  component: (resolve) => require(['@/views/home'], resolve),
	  redirect: 'index',
	  children: [{
		  name: 'index',
		  path: 'index',
		  component: (resolve) => require(['@/views/index'], resolve),
	  }]
  }]
})

const whiteList = ['/login', '/register'];

router.beforeEach((to, from, next) => {
	console.log('from', from, 'to', to)
	// 如果请求地址不在白名单
	if (whiteList.indexOf(to.path) == -1) {
		if (!getLoginUser()) {
			next({path: '/login'})
			return
		}
		if (store.state.menu.menuList.length == 0) {
			store.dispatch('setMenuList').then(res => {
				console.log('store.state.menu', store.state.menu)
				next({...to, replace: true})
			})
		} else {
			next()
		}
		return
	}
	// 在白名单
	next()
})

export default router;